package com.sky.Task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @version 1.0
 * @Author 郭腾高
 * @Date 2024/10/7 18:52
 */

@Component  //交给bean容器管理
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;
    //处理支付超时订单
    @Scheduled(cron = "0 1 * * * ?") //指定任务什么时候触发
    public void processTimeoutOrder(){
         //查询数据库查出订单时间小于前15分钟的进行修改状态了修改时间
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        List<Orders> byStatusAndOrderTimeLT = orderMapper.getByStatusAndOrderTimeLT(Orders.PENDING_PAYMENT, time);
        if (byStatusAndOrderTimeLT != null && byStatusAndOrderTimeLT.size()>0) {
            for (Orders orders : byStatusAndOrderTimeLT) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("订单超时,自动取消");
                orders.setCancelTime(LocalDateTime.now());
                orderMapper.update(orders);
            }
        }
    }

    //处理订单状态为已完成
    @Scheduled(cron = "0 0 1 * * ?") //指定任务什么时候触发
    public void processDeliveryOrder(){
        //查询数据库查出前一天派送中的订单并更改为已完成
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);
        List<Orders> byStatusAndOrderTimeLT = orderMapper.getByStatusAndOrderTimeLT(Orders.DELIVERY_IN_PROGRESS, time);
        if (byStatusAndOrderTimeLT != null && byStatusAndOrderTimeLT.size()>0){
          for (Orders orders : byStatusAndOrderTimeLT) {
            orders.setStatus(Orders.COMPLETED);
            orderMapper.update(orders);
          }
        }
    }

}
